<template>
  <div class="container app-container">
    <div
      class="title"
      style="
        margin: 20px 0 20px 0;
        height: 20px;
        line-height: 20px;
        border-left: 1px solid #ccc;
        text-indent: 15px;
      "
    >
      基本信息
    </div>

    <div class="form">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        :validate-on-rule-change="false"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="归属企业" prop="companyId">
              <el-select
                v-model="form.companyId"
                filterable
                placeholder="请选择"
                @change="handleCompanyProject(form.companyId)"
              >
                <el-option
                  v-for="dict in companyList"
                  :key="dict.id"
                  :label="dict.companyNickName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="所属项目" prop="projectId">
              <el-select v-model="form.projectId" filterable placeholder="请选择">
                <el-option
                  v-for="dict in projectList"
                  :key="dict.id"
                  :label="dict.projectName"
                  :value="dict.id"
                />
              </el-select>
              <el-button
                style="margin-left: 10px"
                icon="el-icon-plus"
                type="text"
                @click="toSaveProject"
              >
                新增项目
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="需求船舶" prop="shipNeeded">
              <el-table :data="needShipList">
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column label="船舶类型" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.typeName"
                      filterable
                      placeholder="请选择"
                      size="mini"
                      @change="setShipNeed"
                    >
                      <el-option
                        v-for="dict in shipDataList"
                        :key="dict.info"
                        :label="dict.info"
                        :value="dict.info"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <el-input
                      placeholder="请输入内容"
                      v-model="scope.row.amount"
                      size="mini"
                      @input="setShipNeed"
                    >
                      <template slot="append">艘</template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <span v-if="scope.$index == 0">-</span>
                    <el-button
                      v-else
                      type="text"
                      style="color: red"
                      @click="delNeedShipList(scope.$index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 15px">
                <el-button type="primary" plain size="mini" @click="addNeedShipList"
                  >添加</el-button
                >
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="订单有效时间" prop="endDate">
              <el-date-picker
                v-model="timeArr"
                style="width: 220px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="截止日期"
                @change="setTime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 表单项放这里 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contacts">
              <el-input
                v-model="form.contacts"
                placeholder="请输入"
                maxlength="10"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人手机号" prop="contactPhone">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入"
                maxlength="11"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input
                style="width: 500px"
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                maxlength="500"
                size="medium"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="footer">
      <el-button size="mini" type="primary" @click="submitForm" class="submit-btn" v-preventReClick
        >确认保存</el-button
      >
    </div>
  </div>
</template>

<script>
// 导入接口方法
import { shipTypeEnum, getProjectListByCompany } from '@/api/common';
import {
  getOrderProjectDetail,
  addOrderProject,
  editOrderProject,
  getCompanySelectList,
} from '@/api/orders/orderProject';

export default {
  // 要改命名，比如课程编辑页可以叫 courseAddOrUpdate
  name: 'CourseAddOrUpdate',
  dicts: [],
  components: {},
  data() {
    return {
      // 标题
      title: '',
      // 初始化 id 为 null
      id: null,
      // 初始化 isEdit 为 false
      isEdit: false,
      // 表单参数
      form: {
        companyId: null,
        projectId: null,
        startDate: null,
        endDate: null,
        shipNeeded: null,
        contacts: null,
        contactPhone: null,
        remark: null,
      },
      companyList: [],
      shipDataList: [],
      // 表单校验
      rules: {
        companyId: [{ required: true, message: '归属企业不能为空', trigger: 'blur' }],
        projectId: [{ required: true, message: '所属项目不能为空', trigger: 'blur' }],
        shipNeeded: [{ required: true, message: '需求船舶不能为空', trigger: 'change' }],
        endDate: [{ required: true, message: '订单有效时间不能为空', trigger: 'blur' }],
        contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        contactPhone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/, message: '手机号格式错误', trigger: 'blur' },
        ],
      },
      needShipList: [{ typeName: '', amount: 0 }],
      timeArr: [],
      projectList: [],
    };
  },
  created() {
    // 通过 $route.params 获取路由参数
    this.id = this.$route.query.id ? this.$route.query.id : null;
    // 判断是否存在 id 参数
    this.isEdit = !!this.id;
    if (this.isEdit) {
      // 如果存在 id 参数，则说明当前页面是修改状态
      // 可以根据 id 参数获取需要修改的数据
      this.getDetail(this.id);
    } else {
      // 如果不存在 id 参数，则说明当前页面是新增状态
    }
  },
  mounted() {
    this.handleShipQuery();
    this.handleCompanyQuery();
  },
  methods: {
    //删除需求船舶某一项
    delNeedShipList(index) {
      this.$delete(this.needShipList, index);
    },
    //添加需求船舶
    addNeedShipList() {
      this.needShipList.push({ typeName: '', amount: 0 });
    },

    // 获取船舶
    handleShipQuery() {
      shipTypeEnum().then((res) => {
        this.shipDataList = res.data;
      });
    },

    // 获取企业
    handleCompanyQuery() {
      getCompanySelectList().then((res) => {
        this.companyList = res.data;
      });
    },

    //获取企业下的所属项目
    handleCompanyProject(companyId) {
      this.form.projectId = '';
      getProjectListByCompany(companyId).then((res) => {
        this.projectList = res.data;
      });
    },

    //新增项目跳转
    toSaveProject() {
      this.$router.push({
        path: '/project/list/save/save',
        query: { companyId: this.form.companyId },
      });
    },

    /** 获取form表单数据 */
    async getDetail(id) {
      try {
        const res = await getOrderProjectDetail({ id: id });
        if (res.code == 200) {
          const {
            companyId,
            projectId,
            startDate,
            endDate,
            shipNeeded,
            shipNeededArray,
            contacts,
            contactPhone,
            remark,
          } = res.data;
          this.handleCompanyProject(companyId);
          this.timeArr = [startDate, endDate];
          this.needShipList = shipNeededArray;
          this.form = {
            companyId,
            projectId: String(projectId),
            startDate,
            endDate,
            shipNeeded,
            contacts,
            contactPhone,
            remark,
          };
        }
      } catch (err) {
        console.error(err);
      }
    },
    //设置时间
    setTime() {
      this.form.startDate = this.timeArr[0] || null;
      this.form.endDate = this.timeArr[1] || null;
    },
    //设置需求船舶
    setShipNeed() {
      let arr = [];
      this.needShipList.forEach((item) => {
        if (item.amount > 0 && item.typeName) {
          arr.push(`${item.typeName}:${item.amount}`);
        }
      });
      this.form.shipNeeded = arr.join(',');
    },
    /** 提交按钮 */
    submitForm() {
      this.setTime();
      this.setShipNeed();
      this.form.createType = '1';
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.id != null) {
            this.$confirm('确定修改当前内容', '确定保存', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用修改接口
                this.handleUpdate();
              })
              .catch(() => {});
          } else {
            this.$confirm('确定发布', '确定发布', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用新增接口
                this.handleAdd();
              })
              .catch(() => {});
          }
        }
      });
    },

    /** 新增 */
    async handleAdd() {
      let saveData = {
        ...this.form,
      };
      saveData.createType = '1';
      this.$modal.loading('正在新增...');
      const data = await addOrderProject(saveData);
      this.$modal.closeLoading();
      if (data.code == 200) {
        this.$message.success(data.msg);
        this.$router.back();
      }
    },

    /** 更新 */
    async handleUpdate() {
      let saveData = {
        ...this.form,
      };
      // 预处理接口传参
      saveData.id = this.id;
      this.$modal.loading('正在保存...');
      const data = await editOrderProject(saveData);
      this.$modal.closeLoading();
      if (data.code == 200) {
        this.$message.success(data.msg);
        this.$router.back();
      }
    },

    /** 关闭按钮 */
    close() {
      // 跳转地址 和 携带参数
      const obj = {
        path: '/orders/ship/list',
        query: {
          t: Date.now(),
          pageNum: this.$route.query.pageNum,
        },
      };
      this.$tab.closeOpenPage(obj).then(() => {
        this.$tab.refreshPage(obj);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
}

.submit-btn {
  position: fixed;
  bottom: 10px;
  left: 50%;
}
</style>
